package com.meitianhui.convenitenbuy.module.wallet.presenter;

import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseResponse;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.http.ResponseObserver;
import com.meitianhui.convenitenbuy.main.model.bean.UserToken;
import com.meitianhui.convenitenbuy.module.wallet.contract.WalletChangeRechargeContract;
import com.meitianhui.convenitenbuy.module.wallet.http.WalletApiDataSource;
import com.meitianhui.convenitenbuy.module.wallet.model.AlipayResultBean;
import com.meitianhui.convenitenbuy.module.wallet.model.PayResultBean;
import com.meitianhui.convenitenbuy.module.wallet.model.RechargeBackInfoBean;
import com.meitianhui.convenitenbuy.module.wallet.ui.activity.WalletChangeRechargeActivity;
import com.meitianhui.convenitenbuy.util.IDUtil;
import com.meitianhui.convenitenbuy.util.LogUtils;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.SystemUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by Administrator on 2017/11/2.
 */

public class WalletChangeRechargePresenter implements WalletChangeRechargeContract.Presenter {

    private WalletChangeRechargeActivity context;
    private final WalletChangeRechargeContract.View view;
    private Gson gson;
    private final IWXAPI wxApi;

    public WalletChangeRechargePresenter(WalletChangeRechargeActivity view,
                                         WalletChangeRechargeActivity context) {
        this.view = view;
        this.context = context;
        wxApi = WXAPIFactory.createWXAPI(context, Constants.WX_APP_ID, true);
    }

    @Override
    public void attachView(Object view) {
    }

    @Override
    public void detachView() {
    }

    @Override
    public void createOrder(boolean mode, String price) {
        UserToken token = InfoProvider.getUserToken(App.getInstance());
        String userToken = token.getUser_token();
        String service = "finance.balanceRecharge";

        Map<String, String> params = new HashMap<>();
        params.put("data_source", Constants.CUSTOM_APP);
        params.put("payment_way_key", mode ? Constants.ALIPAY_APY : Constants.WECHAT_APY);
        params.put("detail", "现金充值");
        params.put("amount", price);
        params.put("out_trade_no", IDUtil.getOutTradeNo());
        params.put("member_id", token.getMember_id());
        gson = new Gson();
        params.put("out_trade_body", gson.toJson(params));
        String jsonParams = gson.toJson(params);

        WalletApiDataSource.getInstance()
                .getRechargeOrder(userToken, service, jsonParams)
                .subscribe(new ResponseObserver<BaseResponse<RechargeBackInfoBean>>(App.getInstance()) {
                    @Override
                    public void onSuccess(BaseResponse<RechargeBackInfoBean> response) {
                        LogUtils.d("--------------------", "qqqqqqqqqqqqq");
                        view.cancelLoading();
                        if (response.data == null) {
                            view.createOrderFail();
                            return;
                        }

                        RechargeBackInfoBean result = response.data;
                        if (mode) {
                            wakeUpAliPay(result);
                        } else {
                            wakeUpWeChat(result);
                        }
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        view.cancelLoading();
                        view.showError(msg);
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        super.onFailure(e);
                    }
                });
    }

    private void wakeUpAliPay(RechargeBackInfoBean bean) {
        String orderInfo = bean.getAlipay_params();
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                PayTask alipay = new PayTask(context);
                String result = alipay.pay(orderInfo, true);
                emitter.onNext(result);
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                AlipayResultBean payResult = new AlipayResultBean(s);
                String resultInfo = payResult.getResult();

                String resultStatus = payResult.getResultStatus();
                // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                if (TextUtils.equals(resultStatus, "9000")) {
                    TipUtils.showToast(context, context.getString(R.string.wallet_change_recharge_success), 1);
                    RxBus.get().post(new PayResultBean(Constants.PAY_RESULT_SUCCESS));
                    context.finish();
                } else {
                    // 判断resultStatus 为非“9000”则代表可能支付失败
                    // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，
                    // 最终交易是否成功以服务端异步通知为准（小概率状态）
                    if (TextUtils.equals(resultStatus, "8000")) {
                        TipUtils.showToast(context, context.getString(R.string.wallet_change_recharge_confirming), 3);
                    } else {
                        // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                        TipUtils.showToast(context, context.getString(R.string.wallet_change_recharge_fail));
                    }
                }
            }
        });
    }

    public void wakeUpWeChat(RechargeBackInfoBean result) {
        boolean ifInstall = SystemUtils.isWXAppInstalledAndSupported(context, result.getAppid());
        if (!ifInstall) {
            TipUtils.showToast(context, context.getString(R.string.wallet_change_recharge_order_wechat_uninstall));
            return;
        }
        PayReq req = new PayReq();
        req.appId = result.getAppid();
        req.nonceStr = result.getNoncestr();
        req.packageValue = result.getPackageValue();
        req.partnerId = result.getPartnerid();
        req.prepayId = result.getPrepayid();
        req.timeStamp = result.getTimestamp();
        req.sign = result.getSign();
        wxApi.registerApp(result.getAppid());
        wxApi.sendReq(req);
        LogUtils.d("--------------------", "eeeeeeeeeeee");
    }

}
